﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Enter.Mvc.Base.Controllers;
using Enter.Services.Mail;
using Enter.Services.DataCache;
using System.Web.Mvc;
using Enter.Mvc.Mall.Model.User;
using Enter.Mvc.Mall.Model;
using Enter.Entity;
using System.Text.RegularExpressions;
using Enter.Common;
using Enter.Common.validcode;
using System.Drawing;
using Newtonsoft.Json;

namespace Enter.Mvc.Mall.Controllers
{
    public class UserController : BaseControllers
    {
          private readonly ICache icache;
        private readonly IMail imail;

        public UserController(ICache cache, IMail mail)
        {
            this.icache = cache;
            this.imail = mail;
        }
        public ActionResult Index()
        {
            return View();
        }

        #region 登陆

        public ActionResult LogOn()
        {
            return View();
        }
        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            var results = new JsonResultModel();
            try
            {
                if (ValidateUser(model))
                {
                    // T201_UserEntity UserLogin
                    T201_UserEntity UserLogin = imail.UserLogin(model.UserName, model.Password);
                    if (UserLogin != null)
                    {
                        UserInfo user = new UserInfo();
                        user.UserID = UserLogin.UIID;
                        user.UserName = UserLogin.UName;
                        user.UserType = (UserInfo.EnumUserType)(int)UserLogin.UserType;
                        user.ShopNo = UserLogin.ShopNo;
                        UserInfo.CurrentUser = user;
                        if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                          && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                        {
                            results.ResultCode = "00";

                            results.ResultMsg = "登陆成功";
                        }
                        else
                        {
                            results.ResultCode = "00";
                            results.ResultMsg = "登陆成功";
                        }
                    }
                    else
                    {
                        results.ResultCode = "01";
                        results.ResultMsg ="用户名或密码错误，请核对后重新输入";
                    }
                }
            }
            catch (Exception ex)
            {

                results.ResultCode = "01";
                results.ResultMsg = ex.Message;
            }
            
              

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
             return Json(results);
        }
        private bool ValidateUser(LogOnModel model)
        {
            if (String.IsNullOrEmpty(model.UserName)) throw new ArgumentException("用户不能为空");
            if (String.IsNullOrEmpty(model.Password)) throw new ArgumentException("密码不能为空");
            if (this.HttpContext.Session["ValidateCode"] == null || Session["ValidateCode"].ToString() != model.ValidateCode)
            {
                throw new ArgumentException("验证码输入错误");
            }
            return true;
        }
        // **************************************
        // URL: /User/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            UserInfo.CurrentUser=null;

            return RedirectToAction("Index", "Home");
        }
        #endregion

        #region 注册
        public ActionResult Register()
        {
            ViewBag.Title =  "用户注册";
            return View();
        }


        public ActionResult UserRegister(RegisterModel model)
        {
            var results = new JsonResultModel();
          
            try
            {
           
                if (CheckRegister(model))
                {


                    T201_UserEntity user = new T201_UserEntity();
                    user.UName = model.UserName;
                    user.UPWD = model.Password;
                    user.UPhone = model.Phone;
                    user = imail.UserRegister(user);
                    if (user.UIID != 0)
                    {
                        UserInfo Loginuser = new UserInfo();
                        Loginuser.UserID = user.UIID;
                        Loginuser.UserName = model.UserName;
                        Loginuser.ShopNo = "0";
                        UserInfo.CurrentUser = Loginuser;
                        results.ResultCode = "00";
                        results.ResultMsg = "注册成功";
                    }
                    else
                    {
                        results.ResultCode = "01";
                        results.ResultMsg = "注册失败,请检查您输入的信息是否正确";
                    }

                }
            }
            catch (Exception ex)
            {

                results.ResultCode = "01";
                results.ResultMsg = ex.Message;
            }

            return Json(results);
        }
        private bool CheckRegister(RegisterModel model)
        {

            if (String.IsNullOrEmpty(model.UserName)) throw new ArgumentException("用户不能为空");
            if(model.UserName.Length<6||model.UserName.Length>26)
            {
                throw new ArgumentException("用户名长度为6-26个字符,一个汉字为两个字符");
            }
            if (!imail.CheckUserName(model.UserName))
            {
                throw new ArgumentException("用户名已存在，请使用其他用户名");
            }
            if (String.IsNullOrEmpty(model.Password)) throw new ArgumentException("密码不能为空");

        
             if (!RegexHelper.RegexValidate("^[a-zA-Z]{1}[a-zA-Z0-9._#*]{5,15}$",model.Password))
             {
                 throw new ArgumentException("密码格式不正确");
             }

         
            if (model.Password != model.ConfirmPassword)
            {
                throw new ArgumentException("密码输入不一致");
            }
            if (String.IsNullOrEmpty(model.Phone)) throw new ArgumentException("手机号码不能为空");

            if (!RegexHelper.RegexValidate("^(13[0-9]{9})|(15[0-9]{9})|(18[0-9]{9})$", model.Phone))
            {
                throw new ArgumentException("手机号输入错误");
            }

            if (this.HttpContext.Session["ValidateCode"] == null || Session["ValidateCode"].ToString() != model.ValidateCode)
            {
                throw new ArgumentException("验证码输入错误");
            }
            return true;
        }

        public ActionResult CheckUserName(string UserName)
        {
            var results = new JsonResultModel();
            if (imail.CheckUserName(UserName))
            {
                results.ResultCode = "00";
                results.ResultMsg = "可以使用";
            }
            else
            {
                 results.ResultCode = "01";
                 results.ResultMsg = "该会员名已被使用";
            }
            return Json(results);
        }

        
        #endregion

        #region 注册成功
        public ActionResult RegisterSuccess()
        {
            ViewBag.UserName = UserInfo.CurrentUser.UserName;
            return View();
        }
        #endregion

        #region 用户收货地址
        public ActionResult SaveAddress(UserAddressModel model)
        {
            var results = new JsonResultModel();

            try
            {

                if (CheckAddress(model))
                {

                    T203_UserAddressEntity entity = new T203_UserAddressEntity();
                    entity.AID = model.ID;
                    entity.UIID = UserInfo.CurrentUser.UserID;
                    entity.AConsignee = model.Consignee;
                    entity.Address = model.Address;
                    entity.APhone = model.Phone;
                    entity.ATel = string.IsNullOrEmpty(model.Tel)?"":model.Tel.Trim('-');
                    entity.AreaCode = model.AreaCode;
                    entity.AZipCode = model.ZipCode;
                    entity.AISDefalut = model.ISDefalut==1?true:false;
                    if (entity.AISDefalut)
                    {
                        imail.CancelDefalutAddbyUID(entity.UIID);
                    }
                    if (imail.SaveUserAddress(entity))
                    {
                        return MyAddress();
                    }
                    else {
                        results.ResultCode = "01";
                        results.ResultMsg = "操作失败,请检查值后重新输入";
                    }
                }
            }
            catch (Exception ex)
            {

                results.ResultCode = "01";
                results.ResultMsg = ex.Message;
            }

            return Json(results);

        }
        public ActionResult DelAddress(string ID)
        {
            var results = new JsonResultModel();

            try
            {
                imail.DelUserAddress(int.Parse(ID), UserInfo.CurrentUser.UserID);
                return MyAddress();
            }
            catch (Exception ex)
            {

                results.ResultCode = "01";
                results.ResultMsg = ex.Message;
            }

            return Json(results);
        }
        public ActionResult UpdateAddress(string ID)
        {
            var results = new JsonResultModel();

            try
            {
                imail.SetDefalutAdd(int.Parse(ID), UserInfo.CurrentUser.UserID);
                return MyAddress();
            }
            catch (Exception ex)
            {

                results.ResultCode = "01";
                results.ResultMsg = ex.Message;
            }

            return Json(results);
        }
        private bool CheckAddress(UserAddressModel model)
        {
            if (String.IsNullOrEmpty(model.Consignee)) throw new ArgumentException("收货人姓名不能为空");
            if (String.IsNullOrEmpty(model.AreaCode)) throw new ArgumentException("所在地区不能为空");
            if (String.IsNullOrEmpty(model.Address)) throw new ArgumentException("街道地址不能为空");
            if (!string.IsNullOrEmpty(model.ZipCode)&&!RegexHelper.RegexValidate("^[0-9]{6}$", model.ZipCode))
            {
               
                    throw new ArgumentException("邮编格式错误");
                
            }
            if (String.IsNullOrEmpty(model.Tel) && String.IsNullOrEmpty(model.Phone))
            {
                throw new ArgumentException("电话号码、手机号选填一项");
            }
            else {
                if (!String.IsNullOrEmpty(model.Phone) && !RegexHelper.RegexValidate("^1[3,4,5,8][0-9]{9}$", model.Phone))
                {
                    throw new ArgumentException("手机号格式错误");
                }
                if (!String.IsNullOrEmpty(model.Tel))
                {
                    string[] m = model.Tel.Split('-');
                    if (!string.IsNullOrEmpty(m[0])&&!RegexHelper.RegexValidate("^[0-9]{3,6}$", m[0]))
                    {
                          throw new ArgumentException("电话号码格式错误");
                    }
                    if (!string.IsNullOrEmpty(m[1])&&!RegexHelper.RegexValidate("^[0-9]{5,10}$", m[1]))
                    {
                        
                            throw new ArgumentException("电话号码格式错误");
                        
                    }
                    if (!string.IsNullOrEmpty(m[2])&&!RegexHelper.RegexValidate("^[0-9]{0,6}$", m[2]))
                    {
                      
                            throw new ArgumentException("电话号码格式错误");
                        
                    }
                }
                
            }
            return true;
        }
        public ActionResult MyAddress()
        {
            List<T203_UserAddressEntity> list = imail.GetUserAdd(UserInfo.CurrentUser.UserID);
            object obj = new { ResultCode="00",list = list };
            string result = JavaScriptConvert.SerializeObject(obj);
            return Content(result);
        }
        #endregion
    }
}
